<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="format-detection" content="telephone=no" />
    <meta name="format-detection" content="email=no" />
    <title>发布话题</title>
    <link rel="stylesheet" href="../../css/api.css">
    <link rel="stylesheet" href="../../css/vant.css">
    <link rel="stylesheet" href="../../css/main.css">
    <style>
        .publish_video {
            margin: 16px 0;
        }

        .van-cell {
            background: none;
        }

        .publish-img-item {
            position: relative;
        }

        .fileInputContainer {
            width: 1rem;
            height: 1rem;
            background: url('https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/circle/yxg_publish.png');
            background-repeat: no-repeat;
            background-size: 1rem 1rem;
            position: relative;
        }

        .fileInputContainer>input {
            width: 1rem;
            height: 1rem;
        }

        .fileInput {
            height: .96rem;
            overflow: hidden;
            font-size: 300px;
            position: absolute;
            right: 0;
            top: 0;
            opacity: 0;
            filter: alpha(opacity=0);
            cursor: pointer;
        }

        .fileVideo {
            width: 1rem !important;
            height: 1rem !important;
            position: relative;
            display: block;
        }

        .up-img img,
        .up-img video {
            object-fit: cover;
        }

        .disable_btn {
            background: #8E8E8E !important;
        }

        .circle_publish_content {
            height: 100px;
            border-bottom: 1px solid #eeeeee;
            margin: 0 16px;
            padding-bottom: 10px;
        }

        .circle_publish_content .van-field__control {
            max-height: 100px;
            overflow-y: scroll;
        }

        .circle_publish_title {
            height: 60px;
            margin: 0 16px;
            border-bottom: 1px solid #eeeeee;
        }

        .select-category {
            height: 60px;
            margin: 0 16px;
            align-items: center;
            border-bottom: 1px solid #eeeeee;
        }

        .select-category .title {
            color: #333;
            font-size: 10px;
            background-color: #eeeeee;
            line-height: 22px;
            border-radius: 11px;
            height: 22px;
            padding: 0 8px;
        }

        .bottom-container {
            padding: 0 16px;
        }

        .publish_btn {
            background-color: #3F8CEC;
            border: none;
            margin-top: 100px;
        }

        /* .bottom-pop{
            padding: 16px;
        } */
        .bottom-pop-cell {
            display: flex;
            flex-direction: column;
        }

        /* .category-item{
            height: 30px;
            color: #333;
            line-height: 30px;
            font-size: 14px;
            border-bottom: 1px solid #dddddd;

        } */
    </style>
</head>

<body>
    <div class="app send-moment" v-cloak>
        <header>
            <div class="flex-x-sb send-moment-header">
                <span class="iconfont goback" @click="back">&#xe66f;</span>
                <!-- <div class="title">{{title}}</div> -->
                <!-- <div class="release-btn" :class="{disable_btn:!submitButtonEnable}"
                 v-if="title == '发话题' || title == '举报'" @click="publishNews" >
                发布
            </div> -->
            </div>
        </header>
        <div class="pt bgFQ">

            <div class="up-img flex-x-s flex-wrap publish_video">
                <div class="container flex-x-s flex-wrap" id="itxst">
                    <div class="publish-img-item item flex-x-s"
                        :data-no="(listSortableVideoOrImages.length - 1 === index)?999:index"
                        :class="{'move': (listSortableVideoOrImages.length - 1 !== index)}"
                        v-for="(item,index) in listSortableVideoOrImages" :key="index">
                        <!--视频显示-->
                        <video class="fileVideo" v-if="item.type === 1 && item.videoUrl" id="player" autoplay loop
                            webkit-playsinline playsinline x5-playsinline style="border-radius: 8px"
                            :poster="item.imageUrl" :src="item.videoUrl">
                        </video>
                        <!--图片显示-->
                        <img class="handle" style="border-radius: 8px" v-if="item.type === 0"
                            :src="item.showImagePath ? item.showImagePath : item.imageUrl" alt="">
                        <!--上传操作-->
                        <div v-if="item.type === -1 && listSortableVideoOrImages.length <= 9"
                            class="handle fileInputContainer" @click.stop="doInputLabel">
                            <input v-if="isUpInput" class="fileInput" type="file" @change="uploadVideoOrImage">
                        </div>
                        <span class="iconfont" v-if="item.type !== -1" @click.stop="sortableRemoveVideoOrImage(index)">
                            <img style="width: .16rem;height: .16rem;" src="https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/delete.png" alt="">
                        </span>
                    </div>
                </div>
            </div>

            <div class=" circle_publish_title">
                <van-field v-model="applyForm.title" rows="1" autosize="{ maxHeight: 100, minHeight: 50 }"
                    type="textarea" placeholder="填写标题会有更多赞哦~" maxlength="20"></van-field>
            </div>

            <div class="circle_publish_content" v-if="isShowContent">
                <van-field v-model="applyForm.content" rows="2" autosize type="textarea" placeholder="填写正文"></van-field>
            </div>

            <div class="select-category flex-x-sb" @click="selectCategory">
                <div class="title">{{currentCategory}}</div>
                <span class="iconfont">&#xe666;</span>
            </div>
            <div class="select-category flex-x-sb" @click="addAddress">
                <div class="title">{{addressName==''?'添加地点':addressName}}</div>
                <span class="iconfont">&#xe666;</span>
            </div>

            <div class="bottom-container">
                <van-button class="publish_btn" round type="info" block size="large" @click="publishNews">发布
                </van-button>
            </div>
        </div>
        <!-- <input id="input" class="fileInput" type="file"> -->

        <van-popup v-model="show" position="bottom" :style="{ height: '30%' }" class="bottom-pop">
            <van-picker title="分类" show-toolbar :columns="columns" @confirm="onConfirmCate" @cancel="onCancelCate"
                @change="onChangeCate" />
        </van-popup>


    </div>
    <script src="../../script/sortable.js"></script>
    <script src="../../script/api.js"></script>
    <script src="../../script/flexible.js"></script>
    <script src="../../script/fastclick.js"></script>
    <script src="../../script/vue.min.js"></script>
    <script src="../../script/iconfont.js"></script>
    <script src="../../script/vant.min.js"></script>
    <script src="../../script/common.js"></script>
    <script src="../../script/restful.js"></script>
    <script src="../../script/uploadImage.js"></script>
    <script src="../../script/businessCommon.js"></script>
    <script src="../../script/aliyun-upload-sdk-1.5.0.min.js"></script>
    <script src="../../script/es6-promise.min.js"></script>
    <script src="../../script/aliyun-oss-sdk-5.3.1.min.js"></script>
    <script src="../../script/common_upload_vod.js"></script>
    <script src="../../script/lrz.bundle.js"></script>
    <script>
        apiready = function () {
            let uploader = null;
            var UIAlbumBrowser = api.require('UIAlbumBrowser');
            vm = new Vue({
                el: '.app',
                data: {
                    isShowContent: false,//是否显示正文
                    currentCategory: '#选择分类',
                    submitButtonEnable: false,
                    message: '',
                    listSortableVideoOrImages: [
                        { imageUrl: 'https://zzzzkj.oss-cn-shanghai.aliyuncs.com/static/tiexie/app/image/image/circle/yxg_publish.png', type: -1, videoId: "", videoUrl: "" }
                    ],
                    uploadFlag: { image: true, vod: true, vodNumber: 0, imgNumber: 0, vodUploadOver: true },
                    title: '',
                    isUpInput: false,
                    systemSet: {
                        onlineBuyEnabled: false,
                        vodLimitSize: 100,
                        imgLimitSize: 100
                    },
                    addressName: '',//地址
                    show: false,//分类
                    columns: [],
                    categoryList: [],
                    // selectCategoryId: null,//选中的频道id

                    applyForm: {
                        channelId: null,//频道id
                        content: null,
                        location: null,
                        medias: null,
                        title: null,
                        type: null//0图片1视频
                    },
                },
                // watch: {
                //     message(val) {
                //         if (val === '' && this.listSortableVideoOrImages.length === 1) {
                //             this.submitButtonEnable = false
                //         }
                //     }
                // },
                mounted: function () {
                    this.initUploadImageModule()

                    this.getCategoryList()
                },
                methods: {
                    //获取分类
                    getCategoryList() {
                        var vm = this
                        release("getListOptions")(10, function (ret, err) {
                            if (ret.data && ret.data.length > 0) {
                                vm.categoryList = ret.data
                                vm.columns = []
                                ret.data.forEach(list => {
                                    vm.columns.push(list.val)
                                })
                            }
                        });
                    },
                    onConfirmCate(value, index) {
                        this.show = false
                        this.currentCategory = value
                        this.applyForm.channelId = this.categoryList[index].id//选中的频道id
                        // this.selectCategoryId = this.categoryList[index].id//选中的频道id
                        // Toast(`当前值：${value}, 当前索引：${index}`);
                    },
                    onChangeCate(picker, value, index) {
                        // Toast(`当前值：${value}, 当前索引：${index}`);
                    },
                    onCancelCate() {
                        // Toast('取消');
                        this.show = false
                    },
                    //选择分类
                    selectCategory() {
                        this.show = true
                    },
                    //添加地址
                    addAddress() {
                        api.openWin({
                            name: 'circle_select_address_win',
                            url: 'circle_select_address_win.html',
                            bounces: false,
                            pageParam: {
                                // topicId: item.topicId,
                            }
                        });
                    },
                    uploadImageEnd(ret) {
                        var index = this.listSortableVideoOrImages.length - 1
                        const media = {
                            imageUrl: ret.data.imagePath,
                            showImagePath: ret.data.showImagePath,
                            type: 0,
                            mediaId: ret.data.resourceId,
                            videoUrl: "",
                            index: index,
                        }
                        this.listSortableVideoOrImages.splice(index, 0, media)
                        vm.submitButtonEnable = true
                    },
                    uploadVideoEnd(ret, video) {
                        var index = this.listSortableVideoOrImages.length - 1
                        const media = {
                            imageUrl: '',
                            type: 1,
                            videoId: ret.data,
                            mediaId: ret.data,
                            videoUrl: video.file,
                            index: index
                        }
                        this.listSortableVideoOrImages.splice(index, 0, media)
                        this.uploadFlag.vodUploadOver = true
                        vm.submitButtonEnable = true
                    },
                    uploadlibraryEnd(ret, video, type) {
                        if (type === 'video') {
                            this.uploadVideoEnd(ret, video)
                        } else {
                            this.uploadImageEnd(ret)
                        }
                    },
                    doMedia() {
                        var vm = this
                        if (vm.listSortableVideoOrImages.length >= 10) {
                            toastMiddle('最多上传9张')
                            return
                        }
                        api.actionSheet({
                            title: '',
                            cancelTitle: '取消',
                            buttons: ['拍照', '摄像', '相册视频', "相册图片"]
                        }, function (ret1, err) {
                            console.log(JSON.stringify(vm.listSortableVideoOrImages))
                            if (ret1.buttonIndex == 1) {
                                if (!vm.checkHasVideo(false)) {
                                    commonDoPic(function (ret2) {
                                        console.log('上传图片返回:', JSON.stringify(ret2));
                                        vm.uploadImageEnd(ret2)
                                        vm.isShowContent = true
                                    })
                                }
                            } else if (ret1.buttonIndex == 2) {
                                if (!vm.checkHasImg() && !vm.checkHasVideo(false)) {
                                    commonDoCamera('TOPICNEW', function (ret2, video) {
                                        console.log('上传视频返回:', JSON.stringify(ret2));
                                        vm.uploadVideoEnd(ret2, video)
                                        vm.isShowContent = false

                                    })
                                }
                            } else if (ret1.buttonIndex == 3) {
                                if (!vm.checkHasImg() && !vm.checkHasVideo(false)) {
                                    commonDoLibrary('video', 'TOPICNEW', function (ret2, video, type) {
                                        console.log('上传相册视频:', JSON.stringify(ret2));
                                        vm.uploadlibraryEnd(ret2, video, type)
                                        vm.isShowContent = false

                                    }, (2 - vm.listSortableVideoOrImages.length))
                                }

                            } else if (ret1.buttonIndex == 4) {
                                if (!vm.checkHasVideo(false)) {
                                    commonDoLibrary('image', 'TOPICNEW', function (ret2, video, type) {
                                        console.log('上传相册图片:', JSON.stringify(ret2));
                                        vm.uploadlibraryEnd(ret2, video, type)
                                        vm.isShowContent = true

                                    }, (10 - vm.listSortableVideoOrImages.length))
                                }
                            }
                        })
                    },

                    checkHasImg() {
                        var imgFlag = false
                        vm.listSortableVideoOrImages.forEach(item => {
                            if (item.type == 0) {
                                toastMiddle('图片和视频不能同时上传')
                                imgFlag = true
                            }
                        });

                        return imgFlag
                    },
                    checkHasVideo(hideToast) {
                        var videoFlag = false
                        vm.listSortableVideoOrImages.forEach(item => {
                            if (item.type == 1) {
                                if (!hideToast) {
                                    toastMiddle('图片和视频不能同时上传,且视频只能上传一个')
                                }
                                videoFlag = true
                            }
                        });
                        return videoFlag
                    },
                    doInputLabel() {
                        const resultList = api.hasPermission({
                            list: ['camera', 'photos']
                        });
                        if (resultList[0].granted && resultList[1].granted) {
                            this.doMedia()
                        } else {
                            const ishasCameraOrPhotos = $api.getStorage('ishasCameraOrPhotos');
                            if (!ishasCameraOrPhotos) {
                                $api.setStorage('ishasCameraOrPhotos', '1');
                                api.requestPermission({
                                    list: ['camera', 'photos'],
                                }, function (ret, err) {
                                    if (ret && ret.list && ret.list.length > 0 && ret.list[0].granted && ret.list[1].granted) {
                                        this.doMedia()
                                    }
                                });
                            } else {
                                toastMiddle('权限已关闭，请手动打开相机权限')
                            }
                        }
                    },

                    checkIsVideo() {
                        console.log(JSON.stringify(this.listSortableVideoOrImages))
                    },

                    // /**
                    //  * 检查是否可以发布
                    //  */
                    // checkCouldPublish: function () {
                    //     this.submitButtonEnable = !(this.listSortableVideoOrImages.length === 1 && this.message === "")
                    // },

                    /**
                     * 发布
                     */
                    publishNews() {
                        // if (!this.submitButtonEnable) {
                        //     return false;
                        // }
                        // this.submitButtonEnable = false
                        const vm = this;
                        if (vm.listSortableVideoOrImages.length === 1) {
                            toastMiddle("请上传视频或图片");
                            return false
                        }

                        if (!vm.uploadFlag.vodUploadOver) {
                            toastMiddle("视频还没有上传结束，请耐心等待！")
                            return false
                        }

                        if (!vm.applyForm.title) {
                            toastMiddle("请填写标题！");
                            return false
                        }

                        if (vm.checkHasVideo(true)) {
                            vm.applyForm.type = 1//视频
                        } else {
                            vm.applyForm.type = 0//图文
                        }

                        if (!vm.applyForm.content && vm.applyForm.type == 0) {
                            toastMiddle("请填写正文！");
                            return false
                        }

                        if (vm.applyForm.channelId == null) {
                            toastMiddle("请选择分类！");
                            return false
                        }

                        vm.listSortableVideoOrImages.splice(vm.listSortableVideoOrImages.length - 1, 1)
                        const medias = []

                        vm.listSortableVideoOrImages.forEach(img => medias.push(img.mediaId))

                        vm.applyForm.medias = medias

                        // const param = { content: vm.message, medias: medias }
                        fnPost(interfaces.CONTENT_MODULE.CIRCLE.PUBLISH_NEWS, vm.applyForm, (ret) => {
                            if (ret && ret.code === RESPONSE_OK) {
                                if (vm.applyForm.type == 1) {
                                    toastMiddle("发布成功，请等待平台审核!")
                                    let myVideo = document.getElementById('player')    //对应video标签的ID
                                    myVideo.pause()
                                } else {
                                    toastMiddle("发布成功!")
                                }

                                setTimeout(() => {
                                    api.sendEvent({ name: 'refreshAllTopic' });
                                    setTimeout(() => {
                                        api.closeWin()
                                    }, 500)
                                }, 1000)
                            } else {
                                toastBottom(ret ? ret.msg : '');
                            }
                        }
                        );
                    },

                    back() {
                        api.closeWin();
                    },

                    //--------------------BEGIN INIT DATA------------------------
                    /**
                     * 初始化系统设置
                     */
                    initSystemSet: function () {
                        let vm = this
                        common('getSystemSet')({}, function (ret) {
                            vm.systemSet.onlineBuyEnabled = ret.data.onlineBuyEnabled
                            vm.systemSet.vodLimitSize = Number(ret.data.maxVideoSize) / 1024
                            vm.systemSet.imgLimitSize = Number(ret.data.maxImageSize) / 1024
                        })
                    },
                    //--------------------INIT DATA END------------------------

                    //--------------------BEGIN INIT DATA------------------------
                    /**
                     * 初始化上传图片拖动模块
                     */
                    initUploadImageModule: function () {
                        let vm = this
                        dragDropSortUploadImage('#itxst', (arr) => {
                            let sort = []
                            sort = JSON.parse(JSON.stringify(vm.listSortableVideoOrImages))
                            for (let i = 0; i < arr.length - 1; i++) {
                                vm.listSortableVideoOrImages[i] = sort[arr[i]]
                            }
                        })
                    },
                    /**
                     * 上传视频和图片
                     */
                    uploadVideoOrImage: function (event) {
                        let vm = this;
                        if (event.target.files.length > 0) {
                            // for (let i = 0; i < event.target.files.length; i++) {
                            const file = event.target.files[0];
                            if (!file) {
                                toastMiddle("请先选择需要上传的文件!");
                                return false;
                            }
                            if (file.type.indexOf('image') > -1) {
                                if (!vm.checkUploadFileSize(file, "image")) {
                                    return false;
                                }
                                vm.uploadImage(file);
                            } else if (file.type.indexOf('video') > -1) {
                                if (vm.uploadFlag.vodNumber === 1) {
                                    vm.uploadFlag.vod = false;
                                    toastMiddle("视频到达上限!");
                                    return false;
                                }
                                if (!vm.checkUploadFileSize(file, "video")) {
                                    return false;
                                }
                                vm.uploadVideo(file);
                            } else {
                                toastMiddle('只能上传图片或者视频');
                                return false;
                            }
                        }
                    },
                    /**
                     * 上传图片
                     * @param file
                     */
                    uploadImage: function (file) {
                        let vm = this
                        vm.submitButtonEnable = false
                        lrz(file)
                            .then(function (rst) {
                                // 处理成功会执行
                                const spliceBase64 = rst.base64.substring(rst.base64.indexOf(',') + 1);
                                fnPostUpData(interfaces.CONTENT_MODULE.UPLOAD_IMAGE, { base64Image: spliceBase64 }, true, (ret) => {
                                    if (ret && ret.code === RESPONSE_OK) {
                                        const media = {
                                            imageUrl: ret.data.imagePath,
                                            type: 0,
                                            mediaId: ret.data.resourceId,
                                            videoUrl: ""
                                        }
                                        vm.listSortableVideoOrImages.splice(vm.listSortableVideoOrImages.length - 1, 0, media)
                                        vm.submitButtonEnable = true
                                    } else {
                                        toastMiddle(ret ? ret.msg : '');
                                    }
                                })
                            })
                        if (vm.listSortableVideoOrImages.length >= 10) {
                            vm.listSortableVideoOrImages.splice(index + 1, 1)
                        }
                    },
                    /**
                     * 上传视频
                     * @param file
                     */
                    uploadVideo: function (file) {
                        let vm = this
                        vm.submitButtonEnable = false
                        const userData = '{"Vod":{}}';
                        if (uploader) {
                            uploader.stopUpload()
                        } else {
                            uploader = createUploader("TOPICNEW", (ret) => {
                                vm.videoUploadOver(ret)
                            })
                        }
                        const media = { imageUrl: '', type: 1, videoId: '', videoUrl: getObjectURL(file) }
                        vm.$nextTick(() => {
                            vm.listSortableVideoOrImages.splice(vm.listSortableVideoOrImages.length - 1, 0, media)
                        })
                        vm.uploadFlag.vodNumber = vm.uploadFlag.vodNumber + 1
                        if (vm.uploadFlag.vodNumber === 1) {
                            vm.uploadFlag.vod = false
                        }
                        vm.uploadFlag.vodUploadOver = false
                        uploader.addFile(file, null, null, null, userData)
                    },
                    /**
                     * 视频上传结束操作
                     */
                    videoUploadOver: function (uploadInfo) {
                        this.uploadFlag.vodUploadOver = true
                        this.listSortableVideoOrImages[this.listSortableVideoOrImages.length - 2].mediaId = uploadInfo.videoId
                        this.submitButtonEnable = true
                    },
                    /**
                     * 移除视频或者图像
                     */
                    sortableRemoveVideoOrImage: function (index) {
                        // 如果是视频则
                        if (this.listSortableVideoOrImages[index].type === 1) {
                            this.uploadFlag.vodNumber = this.uploadFlag.vodNumber - 1;
                            this.uploadFlag.vod = true;
                        }
                        this.listSortableVideoOrImages.splice(index, 1)

                        // this.checkCouldPublish()
                    },
                    /**
                     * 检查文件大小，如果大于返回false
                     * @param file 待检测文件
                     * @param type 类型
                     */
                    checkUploadFileSize: function (file, type) {
                        const fileSize = file.size / 1024 / 1024;
                        console.log('视频大小：', fileSize);
                        if (type === "video") {
                            if (fileSize >= this.systemSet.vodLimitSize) {
                                toastMiddle('视频大小不要超过' + this.systemSet.vodLimitSize + 'M！');
                                return false;
                            }
                        }
                        if (type === "image") {
                            if (fileSize >= this.systemSet.imgLimitSize) {
                                toastMiddle('图片大小不要超过' + this.systemSet.imgLimitSize + 'M！');
                                return false;
                            }
                        }
                        return true;
                    },
                    //--------------------END------------------------
                },
            })

            api.addEventListener({
                name: 'select-address'
            }, function (ret) {
                var cityData = ret.value.city
                vm.addressName = cityData.name
                vm.applyForm.location = cityData.lon + "," + cityData.lat
                //{"value":{"city":{"uid":"B0FFLJNIDS","name":"街电(惠生堂大药房南翔东方伟业广场店)","type":"B0FFLJNIDS","address":"银翔路609号1层115室","tel":"",
                //"distance":69,"indoorData":"floor:0-- floorName:--- poiId:","lat":31.290426,"lon":121.323425,"province":"上海市","city":"上海市","district":"嘉定区"}}}
                // vm.selectedCityName = ret.value.city.name;
                // this.onSearchChange()
                //  api.sendEvent({ name: 'changeLocation' });
            })
        }
    </script>
</body>

</html>